package com.fangcun.service.api.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fangcun.bean.api.order.request.OrderCardRequest;
import com.fangcun.bean.api.order.response.OrderCardResponse;
import com.fangcun.bean.api.subscribe.request.SubscribeAddRequest;
import com.fangcun.bean.api.subscribe.request.SubscribeMySearchRequest;
import com.fangcun.bean.api.subscribe.response.SubscribeMySearchResponse;
import com.fangcun.bean.sys.PageBean;
import com.fangcun.common.canstant.ErrCode;
import com.fangcun.common.canstant.PublicConstant;
import com.fangcun.common.exception.ProAffairException;
import com.fangcun.common.exception.ProRunTimeException;
import com.fangcun.common.util.PublicMethod;
import com.fangcun.entity.OrderCardActivationPerson;
import com.fangcun.entity.OrderCardNumber;
import com.fangcun.entity.OrderTravelPerson;
import com.fangcun.mapper.OrderCardActivationPersonMapper;
import com.fangcun.mapper.OrderCardNumberMapper;
import com.fangcun.mapper.OrderSubscribeMapper;
import com.fangcun.mapper.OrderTravelPersonMapper;
import com.fangcun.service.api.SubscribeApiService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @作者： 陳曉鬆 @时间： 2020年7月20日 - 上午11:35:10 @description：->
 */
@Service("subscribeApiService")
public class SubscribeApiServiceImpl implements SubscribeApiService {

	@Autowired
	private OrderSubscribeMapper orderSubscribeMapper;
	@Autowired
	private OrderCardNumberMapper orderCardNumberMapper;
	@Autowired
	private OrderTravelPersonMapper orderTravelPersonMapper;
	@Autowired
	private OrderCardActivationPersonMapper orderCardActivationPersonMapper;

	@Override
	@Transactional
	public void insert(SubscribeAddRequest request) throws ProAffairException {
		String checkSubscribe = PublicMethod.checkBeanIsNull(request.getSubscribe());
		checkSubscribe = checkSubscribe.replace("id,", "").replace("createTime,updateTime,", "");
		if (!StringUtils.isEmpty(checkSubscribe)
				&& !("contactEmail,contactSupplyPhone".equals(checkSubscribe) || "contactSupplyPhone".equals(checkSubscribe) || "contactEmail".equals(checkSubscribe))) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		if (request.getPersonList() == null || request.getPersonList().size() == 0) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		List<Long> cardIds = new ArrayList<Long>();
		Map<Long, Integer> peopleNumber = new HashMap<Long, Integer>();
		String number = "";
		for (OrderTravelPerson p : request.getPersonList()) {
			if (StringUtils.isEmpty(p.getName())) {
				throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), "姓名不能为空");
			}
			if (StringUtils.isEmpty(p.getName()) || StringUtils.isEmpty(p.getCardNumberId()) || StringUtils.isEmpty(p.getPhone())) {
				throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), p.getName() + ":" + ErrCode.ERR_PARAMETER.getReturnMsg());
			}
			if (PublicConstant.PERSON_TYPE_NI.equals(p.getCertificateType()) && !PublicMethod.isIDNumber(p.getCertificateNumber())) {
				throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), p.getName() + ":身份证验证错误");
			}
			if (PublicConstant.PERSON_TYPE_NI.equals(p.getCertificateType())) {
				p.setBirthday(p.getCertificateNumber().substring(6, 10) + "-" + p.getCertificateNumber().substring(10, 12) + "-" + p.getCertificateNumber().substring(12, 14));
				if (Integer.valueOf(p.getCertificateNumber().substring(16, 17)) % 2 == 0) {
					p.setGender(PublicConstant.PERSON_GENDER_F);
				} else {
					p.setGender(PublicConstant.PERSON_GENDER_M);
				}
			}
			cardIds.add(p.getCardNumberId());
			if (StringUtils.isEmpty(peopleNumber.get(p.getCardNumberId()))) {
				peopleNumber.put(p.getCardNumberId(), 1);
			} else {
				Integer nowPeopleNumber = peopleNumber.get(p.getCardNumberId()) + 1;
				if (nowPeopleNumber > 2) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "卡号ID:" + p.getCardNumberId() + ",人数操作限制两人");
				}
				peopleNumber.put(p.getCardNumberId(), nowPeopleNumber);
			}
			if (number.contains(p.getCertificateNumber())) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "证件号码:" + p.getCertificateNumber() + ",重复");
			}
			number += p.getCertificateNumber() + ",";
		}
		List<OrderCardNumber> cardList = orderCardNumberMapper.selectByIds(cardIds);
		if (cardList == null || cardList.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "卡号ID不存在");
		}
		for (OrderCardNumber cNumber : cardList) {
			if (cNumber.getCardStatus() == 2) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "卡号ID:" + cNumber.getId() + ",已经被使用");
			}
		}
		request.getSubscribe().setUserId(request.getUserId());
		if (orderSubscribeMapper.insertSelective(request.getSubscribe()) == 0 || request.getSubscribe().getId() == null) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "出行信息添加失败");
		}
		for (OrderTravelPerson p : request.getPersonList()) {
			p.setSubscribeId(request.getSubscribe().getId());
		}
		if (orderTravelPersonMapper.insertByList(request.getPersonList()) != request.getPersonList().size()) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "出行人信息添加失败");
		}
		if (orderCardNumberMapper.updateStatusByIds(cardIds) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "卡号状态修改失败");
		}
	}

	@Override
	@Transactional
	public List<OrderCardResponse> selectCardNumber(OrderCardRequest request) throws ProAffairException {
		List<OrderCardResponse> list = orderCardNumberMapper.select(request);
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return list;
	}

	@Override
	@Transactional
	public OrderCardNumber verificationCardNumber(String cardNumber) throws ProAffairException {
		OrderCardNumber number = orderCardNumberMapper.selectByCardNumber(cardNumber);
		if (number == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (0 == number.getCardStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_CARD_NO_ACTIVATION.getReturnCode(), ErrCode.ORDER_CARD_NO_ACTIVATION.getReturnMsg());
		}
		if (2 == number.getCardStatus()) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "该卡片已经被使用");
		}
		return number;
	}

	@Override
	@Transactional
	public void activationCard(OrderCardActivationPerson request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getName())) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), "姓名不能为空");
		}
		if (StringUtils.isEmpty(request.getPhone())) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), request.getName() + ":" + ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		if (PublicConstant.PERSON_TYPE_NI.equals(request.getCertificateType()) && !PublicMethod.isIDNumber(request.getCertificateNumber())) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), request.getName() + ":身份证验证错误");
		}
		if (PublicConstant.PERSON_TYPE_NI.equals(request.getCertificateType())) {
			request.setBirthday(request.getCertificateNumber().substring(6, 10) + "-" + request.getCertificateNumber().substring(10, 12) + "-"
					+ request.getCertificateNumber().substring(12, 14));
			if (Integer.valueOf(request.getCertificateNumber().substring(16, 17)) % 2 == 0) {
				request.setGender(PublicConstant.PERSON_GENDER_F);
			} else {
				request.setGender(PublicConstant.PERSON_GENDER_M);
			}
		}
		OrderCardNumber number = orderCardNumberMapper.selectByCardNumber(request.getCardNumber());
		if (number == null) {// 新增卡片号码
			number = new OrderCardNumber();
			number.setOrderDetailId(0L);
			number.setCardNumber(request.getCardNumber());
			number.setCardStatus(1);
			if (orderCardNumberMapper.insertSelective(number) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "该卡片激活失败1");
			}
		} else {
			if (1 == number.getCardStatus()) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "改卡片已经激活过");
			}
			if (2 == number.getCardStatus()) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "该卡片已经被使用");
			}
			number.setCardStatus(1);
			if (orderCardNumberMapper.updateByPrimaryKeySelective(number) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "该卡片激活失败2");
			}
		}
		if (orderCardActivationPersonMapper.insertSelective(request) <= 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "该卡片激活失败3");
		}
	}

	@Override
	@Transactional
	public PageInfo<SubscribeMySearchResponse> mySubscribe(PageBean<SubscribeMySearchRequest> request) throws ProAffairException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<SubscribeMySearchResponse> list = orderSubscribeMapper.listForApi(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}

}
